import TodoFilter from "./todoFilter"
import TodoInput from "./todoInput"
import TodoList from "./todoList"
import "./../todolist/index.css"
import { useState, useMemo, useEffect } from "react"
const TodoContainer = () => {

    let data = localStorage.getItem('qf-todos') ?? '[]'
    //将json数据变成对象
    data = JSON.parse(data)
    //todos的数据
    let [todos, setTodos] = useState(data)
    //input组件提升的状态
    let [content, setContent] = useState("")
    //声明3个按钮切换的状态
    let [option, setOption] = useState('all')
    const handleAdd = () => {

        if (!content) {
            return
        }
        let todo = {
            id: Math.random().toString(32).substring(2),
            content,
            completed: false
        }

        setTodos([todo, ...todos])

    }

    //删除数据
    const handleDelete = (id) => {
        let newTodo = todos.filter(todo => todo.id !== id)
        setTodos(newTodo)
    }
    //勾选数据
    const changeTodoState = (id, checked) => {
        let target = todos.find(todo => todo.id === id)
        target.completed = checked
        setTodos([...todos])
    }
    //点击Options组件点击不同按钮的时候,触发的函数
    const handleOptionChange = (option) => {
        setOption(option)
    }
    //点击底部按钮筛选不同的数据
    let newTodos = useMemo(() => {
        if (option === 'all') {
            return [...todos]
        } else if (option === 'completed') {
            return todos.filter(todo => todo.completed)
        } else if (option === "active") {
            return todos.filter(todo => !todo.completed)
        }
    }, [todos, option])

    //计算已完成的数量和未完成的数量
    let completedCount = useMemo(() => {
        return (todos.filter(todo => todo.completed)).length
    }, [todos])
    //未完成的数量
    let activeCount = useMemo(() => {
        return (todos.filter(todo => !todo.completed)).length
    }, [todos])
    //负效应Hook,用于设置todos数据
    useEffect(() => {
        localStorage.setItem('qf-todos', JSON.stringify(todos))
    }, [todos])
    return (
        <div className="container">
            <div className="box">
                Todo List
            </div>
            <TodoInput setContent={setContent} add={handleAdd} />
            <TodoList onCheck={changeTodoState} todos={newTodos} del={handleDelete} />
            <TodoFilter aCount={activeCount} cCount={completedCount} onOptionChange={handleOptionChange} todos={todos} />
        </div>
    )
}

export default TodoContainer


